/*******************************************************************************
 * Copyright (c) 2009 Dop Sun.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Dop Sun - initial API and implementation
 ******************************************************************************/
package com.softao.ming.gde.internal.ui.wizard.export;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.wizard.Wizard;

import com.softao.ming.gde.internal.core.export.GdeApplicationExportInfo;
import com.softao.ming.gde.internal.core.export.GdeApplicationExportOperation;
import com.softao.ming.gde.internal.ui.preferences.InstalledGwt;
import com.softao.ming.gde.internal.ui.preferences.InstalledGwt.GwtDefinition;

/**
 * Guides the user to export the GWT Module.
 */
public class ExportGdeApplicationModuleWizard extends Wizard {

	@SuppressWarnings("unused")
	private final IProject mGdeProject;
	
	private ExportGdeApplicationStep0Page mStep0Page;
	
	/**
	 * @param gwtModuleFile 
	 */
	public ExportGdeApplicationModuleWizard(IProject gwtModuleFile) {
		super();
		mGdeProject = gwtModuleFile;
		
		setWindowTitle("Export");
	}
	
	@Override
	public boolean performFinish() {
		Job job = new Job("Exporting GWT Module.") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				GdeApplicationExportInfo info = mStep0Page.getExportInfo();
				GwtDefinition defaultGwt = getDefaultGwt();
				if (defaultGwt != null) {
					info.setGwtLocation(defaultGwt.getPath());
				}
				GdeApplicationExportOperation operation = new GdeApplicationExportOperation(info);
				try {
					operation.run(monitor);
					return Status.OK_STATUS;
				} catch (CoreException e) {
					e.printStackTrace();
				}
				return Status.CANCEL_STATUS;
			}
		};
		job.schedule();
		return true;
	}
	
	private GwtDefinition getDefaultGwt() {
		for (GwtDefinition gwtDefinition : InstalledGwt.load()) {
			if (gwtDefinition.isDefault()) {
				return gwtDefinition;
			}
		}
		
		return null;
	}
	@Override
	public void addPages() {
		mStep0Page = new ExportGdeApplicationStep0Page("GWT Module");
		addPage(mStep0Page);
	}
}
